#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os

from controller.documentController import DocumentController
from werkzeug.datastructures import FileStorage
from models import db
from models.document import Document
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN


class DocumentService(DocumentController):
    base_dir = os.path.dirname(os.path.dirname(__file__))
    ppt_save_dir = os.path.join(base_dir, 'uploads', 'documents')

    @classmethod
    def upload_document(cls, **kwargs):
        try:
            from flask import g
            user_id = g.user['user_id']
            ppt_id = kwargs.get('ppt_id')
            doc_name = kwargs.get('doc_name', None)
            ppt_file: FileStorage = kwargs.get('file')
            suffix = ppt_file.filename.split('.')[-1]

            if not ppt_file:
                return {'code': RET.PARAMERR, 'message': "文件未上传", 'data': {}}

            if not ppt_id:
                return {'code': RET.PARAMERR, 'message': "ppt_id参数缺失", 'data': {}}

            if doc_name is None:
                doc_name = ppt_file.filename

            # 创建目录
            ppt_save_dir = os.path.join(cls.ppt_save_dir, str(user_id))
            os.makedirs(ppt_save_dir, exist_ok=True)

            # 生成唯一模板ID及保存路径
            doc_id = GenerateID.create_random_id()
            relative_path = os.path.join('uploads', 'documents', str(user_id), f"{doc_id}.{suffix}")
            ppt_file.save(os.path.join(ppt_save_dir, f"{doc_id}.{suffix}"))

            # 插入数据库记录
            document = Document(
                doc_id=doc_id,
                doc_name=doc_name,
                doc_location=relative_path,
                user_id=user_id,
                ppt_id=kwargs.get('ppt_id'),
            )
            db.session.add(document)
            db.session.commit()

            return {'code': RET.OK, 'message': "文档添加成功", 'data': {'doc_id': doc_id, 'doc_name': doc_name, 'create_time': document.create_time}}

        except Exception as e:
            loggings.exception(1, f"Error in add_ppt_template: {e}")
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
